import axios from "axios";
import { DepItem } from "./types";
import * as fs from "node:fs";

// ====== 配置区 ======
const NEXUS_BASE_URL = "http://xxxx/service/rest";
const NEXUS_AUTH = { username: "username", password: "password" };
const REPOSITORY = "npm-hosted";
const OUTPUT_PATH = "./已有的依赖清单.json";
// ====================

const request = axios.create({
  baseURL: NEXUS_BASE_URL,
  auth: NEXUS_AUTH,
});

const getItemList = async (): Promise<DepItem[]> => {
  let itemList: DepItem[] = [];
  let res = await request({
    url: "/v1/components",
    params: { repository: REPOSITORY },
  });
  itemList.push(...res.data.items);
  while (res.data.continuationToken) {
    console.log(
      "continuationToken",
      res.data.continuationToken,
      res.data.items.length
    );
    res = await request({
      url: "/v1/components",
      params: {
        repository: REPOSITORY,
        continuationToken: res.data.continuationToken,
      },
    });
    itemList.push(...res.data.items);
  }
  return itemList;
};

const run = async () => {
  const obj: Record<string, string[]> = {};
  const itemList = await getItemList();
  itemList.forEach((dep) => {
    dep.assets.forEach((asset) => {
      if (!obj[asset.npm.name]) obj[asset.npm.name] = [];
      obj[asset.npm.name].push(asset.npm.version);
    });
  });
  fs.writeFileSync(OUTPUT_PATH, JSON.stringify(obj, null, 2));
};

run();
